package controllers;

import helpers.CrawlerDomainHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.DirectoryModel;
import models.DomainModel;
import models.GoogleAdsenceModel;
import models.GoogleAnalyticModel;
import models.InLinkModel;
import models.IpAddressModel;
import models.KeywordRankingModel;
import services.GetInfoDomain;
import systems.ConfigSystem;
import systems.CurrentProcess;
import systems.RecentlyDomain;
import systems.RecentlyUpdate;

import admin.models.MetaSeoModel;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

import debugs.DomainDebug;

import entities.Domain;
import entities.GoogleAdsense;
import entities.GoogleAnalytic;
import entities.InLink;
import entities.IpAddress;
import entities.KeywordRanking;
import entities.MetaSeo;
import entities.SiteConfig;

public class DomainInfoServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		SiteConfig config = ConfigSystem.getConfigs();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (name == null || name.isEmpty() || !UrlHelper.checkDomain(name)) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		if (!name.equalsIgnoreCase(UrlHelper.getMainDomain(name))) {
			response.sendRedirect("/d/" + UrlHelper.getMainDomain(name));
			return ;
		}
		
		DomainModel domainModel = DomainModel.getInstance();
		Domain domain = domainModel.get(name);
		
		if (domain == null || !domain.isExists()) {
			
			if (domain == null) {
				//Get data
				domain = new Domain();
				domain.setProcessing(true);
				domain.setDomain(name);
			}
			
			
			GetInfoDomain getInfoDomain = new GetInfoDomain(domain);
			getInfoDomain.getSiteInfo();
			
			domain = getInfoDomain.getDomain();
			TreeMap check = getInfoDomain.getCheck();
			
			if (!domain.isExists()) {
				response.sendRedirect("/msg/page-not-found");
				return;
			}
			
			domainModel.insert(domain);
			
			IpAddressModel ipAddressModel = IpAddressModel.getInstance();
			
			//Get more info
			if (domain.isExists()) {
				getInfoDomain.getStep1();
				
				domain = getInfoDomain.getDomain();
				
				domain.setProcessing(false);
				domainModel.insert(domain);
				
				//Get whois data
				if (!domain.getIpAddress().isEmpty()) {
					IpAddress ipAddress = ipAddressModel.get(domain.getIpAddress());
					if (ipAddress == null) {
						ipAddress = new IpAddress();
						ipAddress.setIp(domain.getIpAddress());
						CrawlerDomainHelper crawler = new CrawlerDomainHelper();
						ipAddress = crawler.getIp(ipAddress);
						if (ipAddress != null) {
							ipAddressModel.insert(ipAddress);
						}
					}
				}
				
				//Update googleAnalytic model
				if (!domain.getGoogleAnalyticId().isEmpty()) {
					GoogleAnalyticModel googleAnalyticModel = GoogleAnalyticModel.getInstance();
					googleAnalyticModel.insert(domain.getGoogleAnalyticId(), domain.getDomain());
				}
				
				//Update googleAdsense model
				if (!domain.getGoogleAdsenseId().isEmpty()) {
					GoogleAdsenceModel googleAdsenseModel = GoogleAdsenceModel.getInstance();
					googleAdsenseModel.insert(domain.getGoogleAdsenseId(), domain.getDomain());
				}
				
				//Update IpAddress Model
				if (!domain.getIpAddress().isEmpty()) {
					ipAddressModel.insert(domain.getIpAddress(), domain.getDomain());
				}
				
				/*//Update inlink
				if (domain.getOutlink().size() > 0) {
					InLinkModel inlinkModel = InLinkModel.getInstance();
					inlinkModel.insert(domain.getDomain(), domain.getOutlink());
				}*/
				
				CurrentProcess.remove(name);
				RecentlyUpdate.insert(name);
				
				//Update directory
				DirectoryModel directoryModel = DirectoryModel.getInstance();
				directoryModel.insert(domain.getDomain());
			}
		}
		
		if (!domain.isExists()) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		if (domain.getStatus() == -1) {
			response.sendRedirect("/msg/blacklist");
			return;
		}
		
		//Get google analytic
		GoogleAnalyticModel googleAnalyticData = GoogleAnalyticModel.getInstance();
		GoogleAnalytic googleAnalytic = googleAnalyticData.get(domain.getGoogleAnalyticId());
		
		//Get google adsence
		GoogleAdsenceModel googleAdsenceData = GoogleAdsenceModel.getInstance();
		GoogleAdsense googleAdsense = googleAdsenceData.get(domain.getGoogleAdsenseId());
		
		//Get outlink
		InLinkModel oData = InLinkModel.getInstance();
		InLink inlink = oData.get(domain.getDomain());
		
		//Get same domain ip address
		IpAddressModel ipAddressModel = IpAddressModel.getInstance();
		IpAddress ipAddress = null;
		if (!domain.getIpAddress().isEmpty()) {
			ipAddress = ipAddressModel.get(domain.getIpAddress());
		}
		
		//Get keyword
		KeywordRankingModel keywordModel = KeywordRankingModel.getInstance();
		KeywordRanking keyword = keywordModel.get(name);
		
		//Set into recentSiteUpdate
		RecentlyDomain.insert(name);
		
		//Set seo content
		MetaSeoModel metaseoModel = MetaSeoModel.getInstance();
		MetaSeo metaseo = metaseoModel.get("info");
		
		//Cache header
		response.addHeader("Cache-Control", "public");
		response.addHeader("Cache-Control", "max-age=" + 60000);
		
		request.setAttribute("domain", domain);
		request.setAttribute("googleAnalytic", googleAnalytic);
		request.setAttribute("googleAdsense", googleAdsense);
		request.setAttribute("inlink", inlink);
		request.setAttribute("ipAddress", ipAddress);
		request.setAttribute("keyword", keyword);
		request.setAttribute("metaseo", metaseo);
		try {
			request.getRequestDispatcher("/templates/" + config.getTemplate() + "/pages/info.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
